package ntd.util.frame.task.handle.fm;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.log.StaticLog;
import com.c.opt.ComOpt;
import com.ToolOpt;
import com.modular.iot.bo.IotData;
import com.modular.iot.bo.IotDataItem;
import ntd.task.Task;
import ntd.task.bo.TaskInfo;
import ntd.util.UtilCatch;
import ntd.util.UtilThreadPool;
import ntd.util.frame.task.handle.fm.util.ToolFmData;
import ntd.util.modular.things.entity.DeviceData;
import ntd.util.modular.things.entity.DeviceDataItem;
import ntd.util.util.ToolDuration;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public class FmIotDataSync implements Task {

    private ComOpt<DeviceData> deviceDataComOpt = ToolOpt.OPT_T_D_DATA;
    private ComOpt<DeviceDataItem> deviceDataItemComOpt = ToolOpt.OPT_T_D_D_ITEM;

    @Override
    public TaskInfo info() {
        return new TaskInfo("富铭-IOT数据推送任务", "task-fm-iot-data-sync", new FmIotDataSync());
    }

    @Override
    public void execute(Object o) {
        ToolDuration.duration(() -> this.handle(null, "2061"), "富铭-IOT数据推送任务");
    }

    @Transactional
    public void handle(String queryMn, String cn) {
        // 查找时间范围内最近时间节点的数据
        List<DeviceData> deviceDataList = deviceDataComOpt.query().eq("device_code", queryMn).eq("cn", cn)
                .ge("report_time", DateUtil.offsetHour(DateUtil.date(), -24).toStringDefaultTimeZone()).listBean();
        // 遍历24小时内需要同步的数据
        for (DeviceData deviceData : deviceDataList) {
            UtilThreadPool.run(() -> {
                IotData iotData = IotData.transformComPlatform(deviceData);
                // 查询详情数据
                List<DeviceDataItem> deviceDataItems = deviceDataItemComOpt.query().eq("data_id", deviceData.getId()).listBean();
                // 查询子项数据
                iotData.setIotDataItems(CollStreamUtil.toList(deviceDataItems, IotDataItem::transformComPlatform));
                // 富铭开放平台数据推送
                ToolFmData.OPT_FM_DATA.pushData(iotData);
            });
        }
        StaticLog.info("数据同步执行完成...");
    }

    public static void main(String[] args) {
        new FmIotDataSync().handle("", "2061");
    }
}
